<template>
  <el-form
    ref="form"
    id="formalg"
    :model="form"
    label-position="left"
    label-width="110px"
  >
    <input type="hidden" name="algorithmType" :value="type" />
    <div class="base_info">
      <div class="title_label">
        <span>基本信息</span>
      </div>
      <div class="info_box">
        <el-form-item label="算法名称：">
          <el-input
            class="bin_input"
            v-model="form.algorithmName"
            name="algorithmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="方法名称：">
          <el-input
            class="bin_input"
            v-model="form.functionName"
            name="functionName"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本号：">
          <el-input
            class="bin_input"
            v-model="form.algorithmVersion"
            name="algorithmVersion"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本描述：">
          <el-input
            class="bin_input"
            type="textarea"
            v-model="form.versionDescription"
            name="versionDescription"
          ></el-input>
        </el-form-item>
        <el-form-item label="算法：">
          <el-upload
            class="upload-demo"
            ref="upload"
            :multiple="false"
            :limit="1"
            name="algorithmFile"
            :auto-upload="false"
            :show-file-list="true"
            :http-request="uploadFn"
            :on-preview="down1"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="changeFile1"
          >
            <el-button class="bin_button" size="mini">选择文件</el-button>
          </el-upload>
          <div
            class="upload_file_list"
            v-if="form.algorithmFilePath && form.algorithmFilePath.length"
          >
            <div class="file_item">
              <div class="file_name" :title="form.algorithmFilePath">
                {{ form.algorithmFilePath }}
              </div>
              <div
                @click="downLoadFile('0')"
                class="file_btn el-icon-download"
              ></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="说明文档：">
          <el-upload
            class="upload-demo"
            ref="upload1"
            :multiple="false"
            :limit="1"
            name="explanatoryDocumentFile"
            :auto-upload="false"
            :show-file-list="true"
            :http-request="uploadFn"
            :on-preview="down2"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="changeFile2"
          >
            <el-button class="bin_button" size="mini">选择文件</el-button>
          </el-upload>
          <div
            class="upload_file_list"
            v-if="
              form.explanatoryDocumentFilePath &&
              form.explanatoryDocumentFilePath.length
            "
          >
            <div class="file_item">
              <div class="file_name" :title="form.explanatoryDocumentFilePath">
                {{ form.explanatoryDocumentFilePath }}
              </div>
              <div
                @click="downLoadFile('1')"
                class="file_btn el-icon-download"
              ></div>
            </div>
          </div>
        </el-form-item>
        <input type="hidden" name="status" :value="statusvalue" />
        <!-- <el-form-item label="状态：">
          <el-select
            class="bin_select"
            v-model="form.status"
            @change="test"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in statusOption"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="上传人：">
          <el-input
            class="bin_input"
            v-model="form.uploadUser"
            name="uploadUser"
          ></el-input>
        </el-form-item>
      </div>
    </div>
    <div class="param_set">
      <div class="title_label">
        <span>参数设置</span>
        <el-button class="bin_button" size="small" @click="addinput">
          新增
        </el-button>
      </div>
      <div class="params_box">
        <!-- 123 -->
        <div
          class="paramsItem"
          v-for="(item, index) in form.algorithmInputOutputEntityList"
          :key="index"
        >
          <template v-if="item.isInputOrOutput == 0">
            <input
              type="hidden"
              :name="`algorithmInputOutputEntityList[${index}].isInputOrOutput`"
              :value="'0'"
            />
            <div class="params_form_box">
              <div class="form_title">变量{{ index + 1 }}</div>
              <div class="miniform_box">
                <el-form-item label="变量名：">
                  <el-input
                    class="bin_input"
                    v-model="item.variableName"
                    :name="`algorithmInputOutputEntityList[${index}].variableName`"
                  ></el-input>
                </el-form-item>
                <el-form-item label="中文意义：">
                  <el-input
                    class="bin_input"
                    v-model="item.variableChineseName"
                    :name="`algorithmInputOutputEntityList[${index}].variableChineseName`"
                  ></el-input>
                </el-form-item>
                <el-form-item label="阈值：">
                  <el-col :span="10">
                    <el-input
                      class="bin_input"
                      v-model="item.thresholdMinimum"
                      :name="`algorithmInputOutputEntityList[${index}].thresholdMinimum`"
                    ></el-input>
                  </el-col>
                  <el-col class="line" :span="4">—</el-col>
                  <el-col :span="10">
                    <el-input
                      class="bin_input"
                      v-model="item.thresholdMaximum"
                      :name="`algorithmInputOutputEntityList[${index}].thresholdMaximum`"
                    ></el-input>
                  </el-col>
                </el-form-item>
                <input
                  type="hidden"
                  :name="`algorithmInputOutputEntityList[${index}].inputOutputDataType`"
                  :value="inputOutputDataTypeValue(index)"
                />
                <el-form-item label="参数类型：">
                  <el-select
                    filterable
                    class="bin_select"
                    v-model="item.inputOutputDataType"
                    placeholder="请选择参数类型"
                  >
                    <el-option
                      v-for="item in canshuleixing"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                      {{ item.name }}
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item style="display: none" label="排序：">
                  <el-input
                    class="bin_input"
                    v-model="item.inputOrOutputSort"
                    :name="`algorithmInputOutputEntityList[${index}].inputOrOutputSort`"
                  ></el-input>
                </el-form-item>
                <el-form-item label="默认值：">
                  <el-input
                    class="bin_input"
                    v-model="item.defaultValue"
                    :name="`algorithmInputOutputEntityList[${index}].defaultValue`"
                  ></el-input>
                </el-form-item>

                <!-- <el-form-item label="">
                  <el-button class="bin_button" size="small" style="width: 100%">
                    确定
                  </el-button>
                </el-form-item> -->
              </div>
            </div>
            <div class="del" @click="delinput(index)">
              <img
                class="actBtn"
                :src="require('../../../assets/del.png')"
                alt=""
              />
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="output_set">
      <div class="title_label">
        <span>输出设置</span>
        <el-button class="bin_button" size="small" @click="addoutput">
          新增
        </el-button>
      </div>
      <div class="output_box">
        <div
          class="outputItem"
          v-for="(item, index) in form.algorithmInputOutputEntityList"
          :key="index"
        >
          <template v-if="item.isInputOrOutput == 1">
            <input
              type="hidden"
              :name="`algorithmInputOutputEntityList[${index}].isInputOrOutput`"
              :value="'1'"
            />
            <div class="output_form_box">
              <div class="form_title">变量{{ index + 1 }}</div>
              <div class="miniform_box">
                <el-form-item label="变量名：">
                  <el-input
                    class="bin_input"
                    v-model="item.variableName"
                    :name="`algorithmInputOutputEntityList[${index}].variableName`"
                  ></el-input>
                </el-form-item>
                <el-form-item label="中文意义：">
                  <el-input
                    class="bin_input"
                    v-model="item.variableChineseName"
                    :name="`algorithmInputOutputEntityList[${index}].variableChineseName`"
                  ></el-input>
                </el-form-item>
                <el-form-item label="阈值：">
                  <el-col :span="10">
                    <el-input
                      class="bin_input"
                      v-model="item.thresholdMinimum"
                      :name="`algorithmInputOutputEntityList[${index}].thresholdMinimum`"
                    ></el-input>
                  </el-col>
                  <el-col class="line" :span="4">—</el-col>
                  <el-col :span="10">
                    <el-input
                      class="bin_input"
                      v-model="item.thresholdMaximum"
                      :name="`algorithmInputOutputEntityList[${index}].thresholdMaximum`"
                    ></el-input>
                  </el-col>
                </el-form-item>
                <input
                  type="hidden"
                  :name="`algorithmInputOutputEntityList[${index}].inputOutputDataType`"
                  :value="inputOutputDataTypeValue(index)"
                />
                <el-form-item label="参数类型：">
                  <el-select
                    filterable
                    class="bin_select"
                    v-model="item.inputOutputDataType"
                    placeholder="请选择参数类型"
                  >
                    <el-option
                      v-for="item in canshuleixing"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                      {{ item.name }}
                    </el-option>
                  </el-select>
                </el-form-item>

                <!-- <el-form-item label="">
                  <el-button class="bin_button" size="small" style="width: 100%">
                    确定
                  </el-button>
                </el-form-item> -->
              </div>
            </div>

            <div class="del" @click="deloutput(index)">
              <img
                class="actBtn"
                :src="require('../../../assets/del.png')"
                alt=""
              />
            </div>
          </template>
        </div>
      </div>
    </div>
    <div class="edit_btns">
      <el-button class="bin_button" size="small" @click="cancelBtn">
        取消
      </el-button>
      <el-button class="bin_button" size="small" @click="imoprt1">
        开始导入
      </el-button>
    </div>
  </el-form>
</template>

<script>
import http from "@/utils/request";
export default {
  name: "algorithmForm",
  props: {
    type: {
      type: Number,
    },
    clickType: {
      type: Number,
    },
    formObject: {
      type: Object,
      default: {},
    },
  },

  data() {
    return {
      form: {
        algorithmInputOutputEntityList: [],
      },
      statusOption: [
        {
          name: "上架",
          value: "1",
        },
        {
          name: "下架",
          value: "2",
        },
      ],
      canshuleixing: [
        {
          name: "INT类型",
          value: 1,
        },
        {
          name: "DOUBLE类型",
          value: 2,
        },
        {
          name: "DOUBLE数组类型",
          value: 3,
        },
        {
          name: "DOUBLE二维数组类型",
          value: 4,
        },
        {
          name: "STRING类型",
          value: 5,
        },
      ],
      // 算法上传
      isUploadAlgorithmFile: false,
      isUploadAlgorithmDoc: false,
    };
  },
  computed: {
    statusvalue() {
      let value;
      this.statusOption.map((e) => {
        if (this.form.status) {
          if (e.value == this.form.status) {
            value = e.value;
          }
        }
      });
      return value;
    },
  },
  watch: {
    clickType: {
      handler(newVal, oldVal) {
        //打开弹窗的方式 1：算法导入 2：编辑
        console.log("childData changed:", newVal);
        if (newVal == 1) {
          this.form = {
            algorithmInputOutputEntityList: [],
          };
        }
        if (newVal == 2) {
          this.formData();
        }
        return newVal;
        // 如果需要深比较，你可能需要自己实现比较逻辑
      },
      deep: true, // 对于对象或数组，开启深度监听
      immediate: false, // 组件加载时不立即执行
    },
    formObject: {
      handler(newVal, oldVal) {
        // 注意：这里的newVal和oldVal对于对象或数组来说，是引用。
        // 如果你只是改变了对象的属性而没有替换整个对象，这里的新旧值将指向同一个对象。
        console.log("childData changed:", newVal);
        this.formData();
        // 如果需要深比较，你可能需要自己实现比较逻辑
      },
      deep: true, // 对于对象或数组，开启深度监听
      immediate: false, // 组件加载时不立即执行
    },
  },
  created() {},
  mounted() {
    if (this.clickType == 2) {
      // 如果是点编辑进来的  给form重新赋值
      console.log(this.formObject, "点击进来this.formObject");
      if (this.isObjectNotEmpty(this.formObject)) {
        this.formData();
      }
    }

    // Component mounted
  },
  methods: {
    formData() {
      //form重新赋值
      this.form = {
        algorithmName: this.formObject.algorithmName, //算法名称
        functionName: this.formObject.functionName, //方法名称
        algorithmVersion: this.formObject.algorithmVersion, //版本号
        versionDescription: this.formObject.versionDescription, //版本描述
        uploadUser: this.formObject.uploadUser, //上传人
        algorithmFilePath: this.formObject.algorithmFilePath, //算法
        explanatoryDocumentFilePath:
          this.formObject.explanatoryDocumentFilePath, //说明文档
        algorithmInputOutputEntityList: [],
      };
      this.getSetData(this.formObject.id);
    },
    inputOutputDataTypeValue(index) {
      // 假设 isObjectNotEmpty 是一个有效的函数来检查对象是否为空且非null

      if (
        !this.isObjectNotEmpty(this.formObject) ||
        !this.form.algorithmInputOutputEntityList[index] ||
        !this.form.algorithmInputOutputEntityList[index].inputOutputDataType
      ) {
        // 如果 formObject 为空，或者算法输入输出实体列表中的对应项不存在，或者数据类型未定义，则返回 undefined
        return undefined;
      }

      // 使用 find 方法在 canshuleixing 数组中查找匹配项
      const match = this.canshuleixing.find(
        (e) =>
          e.value ===
          this.form.algorithmInputOutputEntityList[index].inputOutputDataType
      );

      // 如果找到匹配项，则返回其 value，否则返回 undefined
      return match ? match.value : undefined;
    },
    cancelBtn() {
      this.$emit("close");
    },
    clearFileList() {
      this.$refs.upload.clearFiles();
      this.$refs.upload1.clearFiles();
    },
    down1() {
      console.log("下载1");
    },
    down2() {
      console.log("下载2");
    },
    downLoadFile(type) {
      console.log(this.formObject, "this.formObject");
      let query = { algorithmId: this.formObject.id, fileType: type };

      http({
        method: "post",
        url: `/underwater-sound/algorithmManagement/downloadFile?algorithmId=${query.algorithmId}&fileType=${query.fileType}`,
        responseType: "blob", // 设置为blob以接收文件
        // data: query,
      })
        .then((response) => {
          let filePath =
            type == "0"
              ? this.formObject.algorithmFilePath
              : this.formObject.explanatoryDocumentFilePath;
          // 使用Windows风格的路径分隔符来分割字符串
          let fileNameWithExt = filePath.split("\\").pop(); // 'pop()' 方法返回数组的最后一个元素

          // 如果后端没有通过 Content-Disposition 提供文件名，则使用默认名
          if (!fileNameWithExt) {
            fileNameWithExt = "downloaded_file.txt"; // 或其他默认文件名
          }
          // 创建一个指向 Blob 的 URL
          const url = window.URL.createObjectURL(response);

          // 创建一个 a 标签并设置其 href 和 download 属性
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", `${fileNameWithExt}`);

          // 将 a 标签添加到 body 中并触发点击事件
          document.body.appendChild(link);
          link.click();

          // 清理：从 DOM 中移除 a 标签并释放 URL 对象
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          // 处理请求错误
          console.error("下载文件时出错:", error);
          // 可以在这里添加更多的错误处理逻辑，比如显示错误消息给用户
        });
    },
    // test () {
    //   if (this.form.status === "1") {
    //     this.$api
    //       .checkSameTypeAlgorithmIsOnline({
    //         algorithmId: "",
    //         algorithmName: this.form.algorithmName,
    //         algorithmType: this.type,
    //       })
    //       .then((res) => {
    //         if (res.code === 200) {
    //           if (!res.result) {
    //             this.$confirm("已有上架的同名称算法，继续提交会添加新版本", "提示", {
    //               confirmButtonText: "确定",
    //               cancelButtonText: "取消",
    //               type: "warning",
    //             })
    //               .then(() => {
    //                 this.$emit("close")
    //               })
    //               .catch(() => {
    //                 this.form.status = ""
    //               })
    //           }
    //         }
    //       })
    //   }
    // },
    addinput() {
      console.log(this.form.algorithmInputOutputEntityList);
      this.$set(
        this.form,
        "algorithmInputOutputEntityList",
        this.form.algorithmInputOutputEntityList.concat({ isInputOrOutput: 0 })
      );
    },
    addoutput() {
      this.$set(
        this.form,
        "algorithmInputOutputEntityList",
        this.form.algorithmInputOutputEntityList.concat({ isInputOrOutput: 1 })
      );
    },
    delinput(idx) {
      this.$set(
        this.form,
        "algorithmInputOutputEntityList",
        this.form.algorithmInputOutputEntityList.filter((item, index) => {
          return index !== idx;
        })
      );
    },
    deloutput(idx) {
      this.$set(
        this.form,
        "algorithmInputOutputEntityList",
        this.form.algorithmInputOutputEntityList.filter((item, index) => {
          return index !== idx;
        })
      );
    },
    uploadFn() {
      // var data = new FormData();
      // let multipartFiles = this.$refs.multipleTable.selection.map((item) => {
      //   return item.raw;
      // });
      // data.append("file", multipartFiles);
      // this.$api
      //   .addTempFile({ multipartFiles: data, fileSource: this.fileRadioValue })
      //   .then((res) => {
      //     console.log(res);
      //   });
    },
    changeFile1(file, fileList) {
      this.isUploadAlgorithmFile = true;
      this.form.algorithmFile = file;
    },
    changeFile2(file, fileList) {
      this.isUploadAlgorithmDoc = true;
      this.form.explanatoryDocumentFile = file;
    },
    imoprt1() {
      //打开弹窗的方式 1：算法导入 2：编辑
      const formData = new FormData(this.$refs["form"].$el);

      if (this.clickType == 1) {
        this.$api
          .sfsjDaoruApi(formData)
          .then((res) => {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.form = {};
            this.clearFileList();
            this.$emit("close");
          })
          .catch((err) => {
            console.log(err);
          });
      }
      if (this.clickType == 2) {
        const formData = new FormData(this.$refs["form"].$el);
        formData.append("id", this.formObject.id);
        console.log("this.form==", this.form);
        console.log("this.formObject==", this.formObject);

        if (this.isUploadAlgorithmFile) {
          formData.set("algorithmFilePath", "");
        } else {
          formData.set("algorithmFilePath", this.formObject.algorithmFilePath);
        }
        if (this.isUploadAlgorithmDoc) {
          formData.set("explanatoryDocumentFilePath", "");
        } else {
          formData.set(
            "explanatoryDocumentFilePath",
            this.formObject.explanatoryDocumentFilePath
          );
        }

        this.$api
          .updateAlgorithm(formData)
          .then((res) => {
            console.log("修改res==", res);
            this.$message({
              message: res.message,
              type: "success",
            });
            this.form = {};
            this.clearFileList();
            this.$emit("close");
            this.isUploadAlgorithmFile = false;
            this.isUploadAlgorithmDoc = false;
            window.location.reload();
          })
          .catch((err) => {
            console.log(err);
          });
      }
      // let formData = new FormData(document.getElementById("formalg"));
      // window.location.reload();
    },
    isObjectNotEmpty(obj) {
      return obj !== null && obj !== undefined && Object.keys(obj).length > 0;
    },
    getSetData(id) {
      // algorithmId
      this.$api
        .getParams({ algorithmId: id })
        .then((res) => {
          // 检查响应结果是否有效
          if (res && res.result) {
            this.form.algorithmInputOutputEntityList = res.result;

            console.log(this.form, "res");
          } else {
            console.error(
              "Failed to retrieve algorithm input/output parameters:",
              res
            );
            // 这里可以添加一些错误处理逻辑，比如设置默认值或通知用户
          }
        })
        .catch((error) => {
          // 处理 API 调用过程中可能发生的任何错误
          console.error("Error fetching algorithm parameters:", error);
          // 类似地，这里也可以添加错误处理逻辑
        });
    },
  },
};
</script>

<style scoped lang="scss">
.edit_btns {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30px;
  padding-bottom: 20px;
}

.title_label {
  background-color: rgba(2, 255, 244, 0.15);
  width: 100%;
  height: 50px;
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 500;
  font-size: 18px;
  color: #fff;
  line-height: 50px;
  text-align: left;
  padding: 0 40px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  align-items: center;
}

::v-deep .el-form-item__label {
  font-family: Source Han Sans CN, Source Han Sans CN;
  font-weight: 500;
  font-size: 18px;
  color: #fff;
}

.info_box,
.params_box,
.output_box {
  padding: 20px 40px;
  padding-bottom: 0;
}

.paramsItem,
.outputItem {
  display: flex;
  justify-content: space-between;
  height: 100%;
  margin-bottom: 20px;

  .params_form_box,
  .output_form_box {
    width: calc(100% - 48px);

    .form_title {
      background-color: rgba(2, 255, 244, 0.1);
      height: 40px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 18px;
      color: #fff;
      line-height: 40px;
      display: flex;
      padding: 0 20px;
      box-sizing: border-box;
    }

    .miniform_box {
      background: rgba(2, 82, 107, 0.2);
      padding: 20px;
      box-sizing: border-box;

      .el-form-item {
        &:last-child {
          margin-bottom: 0;
        }
      }

      .line {
        text-align: center;
        color: #fff;
      }
    }
  }

  .del {
    cursor: pointer;
    width: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(12, 81, 99, 0.5);
  }
}

::v-deep .upload-demo {
  .el-upload-list__item {
    cursor: pointer;
    background: rgba(2, 255, 244, 0.1);

    .el-upload-list__item-name {
      color: #fff;

      .el-icon-document {
        color: #fff;
      }
    }

    .el-icon-close {
      color: #fff;
    }
  }
}

::v-deep .upload_file_list {
  .file_item {
    width: 100%;
    height: 40px;
    font-size: 16px;
    margin-top: 10px;
    display: flex;
    align-items: center;

    .file_name {
      flex: 1 1 auto;
      width: 0;
      height: 100%;
      padding: 0 15px;
      box-sizing: border-box;
      color: #fff;
      cursor: pointer;
      overflow: hidden;
      background-color: rgba(2, 255, 244, 0.2);
    }

    .file_btn {
      cursor: pointer;
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      color: #02fff4;
      font-size: 24px;
      font-weight: 500;
      flex: 0 0 auto;
      margin-left: 10px;
      background-color: rgba(2, 255, 244, 0.2);

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

/* Add your styles here */
</style>
